package vtt.android.tinthethao_ota.fragments;

import vtt.android.library.utils.VttGA;
import vtt.android.tinthethao_ota.R;
import vtt.android.tinthethao_ota.activities.DetailActivity;
import vtt.android.tinthethao_ota.widgets.webview.VideoEnabledWebChromeClient;
import vtt.android.tinthethao_ota.widgets.webview.VideoEnabledWebView;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.android.gms.ads.AdView;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

public class DetailFragment extends BaseWebFragment {

    private VideoEnabledWebView mVideoWebView;
    private VideoEnabledWebChromeClient webChromeClient;
    public boolean mIsVideoFullScreen = false;
    private String mOriginalHost = "";
    private String mOriginalUrl;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		View view = inflater.inflate(R.layout.fragment_details, null, false);
		mProgressBar = (SmoothProgressBar) view.findViewById(R.id.progressbar_loading);
		
		// get webview
		mVideoWebView = (VideoEnabledWebView) view.findViewById(R.id.webView);
		mVideoWebView.setWebViewClient(new WebClient());
		mVideoWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);

        WebSettings webSettings = mVideoWebView.getSettings();
        webSettings.setBuiltInZoomControls(true);
        if (Build.VERSION.SDK_INT >= 11){
            webSettings.setDisplayZoomControls(false);
        }
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // setup webchrome client
        setupWebChromeClient(view);
		
		// mVideoWebView.getSettings().setJavaScriptEnabled(false);
		// load admob
		AdView adView = (AdView) view.findViewById(R.id.adView);
		loadAdmob(adView);
		
		return view;
	}
	
    /**
     * @param rootView
     */
    private void setupWebChromeClient(View rootView) {
        // Initialize the VideoEnabledWebChromeClient and set event handlers
        View nonVideoLayout = rootView.findViewById(R.id.nonVideoLayout); // Your own view, read class comments
        ViewGroup videoLayout = (ViewGroup)rootView.findViewById(R.id.videoLayout); // Your own view, read class comments
        //noinspection all
        View loadingView = mParentAct.getLayoutInflater().inflate(R.layout.view_loading_video, null); // Your own view, read class comments
        webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, loadingView, mVideoWebView) // See all available constructors...
        {
            // Subscribe to standard events, such as onProgressChanged()...
            @Override
            public void onProgressChanged(WebView view, int progress) {
                if (progress >= 100) {
                    mProgressBar.progressiveStop();
                }
            }
        };
        webChromeClient.setOnToggledFullscreen(new VideoEnabledWebChromeClient.ToggledFullscreenCallback()
        {
            @Override
            public void toggledFullscreen(boolean fullscreen)
            {
                VttGA.sendEvent(mParentAct, "Play Video", "Open FullScreen " + fullscreen, null, 0);
                mIsVideoFullScreen = fullscreen;
                // Your code to handle the full-screen change, for example showing and hiding the title bar. Example:
                if (fullscreen)
                {
                    WindowManager.LayoutParams attrs =  mParentAct.getWindow().getAttributes();
                    //attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
                    attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
                    mParentAct.getWindow().setAttributes(attrs);
                    if (android.os.Build.VERSION.SDK_INT >= 14) {
                        // noinspection all
                        mParentAct.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
                    }
                    
                    if(mParentAct instanceof DetailActivity){
                        ((DetailActivity)mParentAct).setSwipeBackEnable(false);
                    }
                }
                else
                {
                    WindowManager.LayoutParams attrs = mParentAct.getWindow().getAttributes();
                    //attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
                    attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
                    mParentAct.getWindow().setAttributes(attrs);
                    if (android.os.Build.VERSION.SDK_INT >= 14)
                    {
                        //noinspection all
                        mParentAct.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                    }
                    
                    if(mParentAct instanceof DetailActivity){
                        ((DetailActivity)mParentAct).setSwipeBackEnable(true);
                    }
                }

            }
        });
        mVideoWebView.setWebChromeClient(webChromeClient);
    }
	
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.menu_detail, menu);
    }
    
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		log.d("VTT>>> action_refresh" + "");
		switch (item.getItemId()) {
		case R.id.action_open_browser:
		    Intent intentBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(mVideoWebView.getUrl()));
            startActivity(intentBrowser);
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}

	/**
	 * load html
	 * @param url
	 */
	public void loadUrl(String url) {
	    if(url != null){
	        mOriginalHost = Uri.parse(url).getHost();
	        mOriginalHost = mOriginalHost.startsWith("www.") ? mOriginalHost.substring(4) : mOriginalHost;
	        mOriginalHost = mOriginalHost.startsWith("m.") ? mOriginalHost.substring(2) : mOriginalHost;
	        log.d("VTT>>>mOriginalHost  " + mOriginalHost);
	        mOriginalUrl = url;
	        mVideoWebView.loadUrl(url);
	    }
	}
	
	@Override
	protected void reloadPage() {
	    if (mVideoWebView != null) {
            mVideoWebView.reload();
        }
	}
	
	class WebClient extends WebViewClient {

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			mProgressBar.progressiveStart();
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			log.d("VTT>>> onPageFinished " + url);
			if(url.contains("bongda24h.vn")){
			    // remove all google ads
			    view.loadUrl(
	                    "javascript: var ads = document.getElementsByClassName('adsbygoogle'); for (var i = 0; i < ads.length; ++i) { var item = ads[i]; item.style.display = 'none';}"
	            );
			}
			
		}

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            log.d("VTT>>> url " + url);
            // prevent user install another app
            if (url.contains("play.google.com/store/apps") 
                    || url.contains("market://details?id=")
                    || url.endsWith(".apk")) {
                return true;
            }

            if (url.endsWith(".mp4") || url.endsWith(".3gp")) {
                VttGA.sendEvent(mParentAct, "Play Video", "Play Mp4,3Gp", null, 0);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.parse(url), "video/*");
                startActivityForResult(intent, 0);
                return true;
            }

            // check host
            String host = Uri.parse(url).getHost();
            if (!host.contains(mOriginalHost)) {
                log.d("VTT>>> host " + host);
                log.d("VTT>>> mOriginalHost " + mOriginalHost);
                //view.loadUrl(mOriginalUrl);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    }
	
    @Override
    public void onPause() {
        stopPlayHtmlVideo();
        super.onPause();
    }

    /**
     * 
     */
    private void stopPlayHtmlVideo() {
        try {
            // prevent crash if video is playing in full screen
            webChromeClient.onBackPressed();
            // pause if video is playing
            Class.forName("android.webkit.WebView")
                    .getMethod("onPause", (Class[]) null)
                    .invoke(mVideoWebView, (Object[]) null);
        } catch (Exception ex) {
            ex.printStackTrace();
            if(getActivity() == null){
                return;
            }
            VttGA.sendException(mParentAct, ex.getMessage());
        }
    }
    
    @Override
    public void goBackWebView() {
        if (!webChromeClient.onBackPressed()) {
            if (mVideoWebView != null && mVideoWebView.canGoBack()) {
                mVideoWebView.goBack();
            } else {
                stopPlayHtmlVideo();
//                ((DetailActivity)mParentAct).scrollToFinishActivity();
                ((DetailActivity)mParentAct).finish();
            }
        }
    }
    
    @Override
    public void onDestroy() {
        if (mWebView != null) {
            mWebView.stopLoading();
            mWebView.setVisibility(View.GONE);
            ViewGroup parent = (ViewGroup) mWebView.getParent();
            if (parent != null) {
                parent.removeView(mWebView);
            }
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }
}
